package com.example.ktapplication.utils
import android.content.Context
import android.content.SharedPreferences
import com.example.ktapplication.AppGlobals

class SpUtils {

    val prefs: SharedPreferences by lazy {
        AppGlobals.getApplication().getSharedPreferences("SP", Context.MODE_PRIVATE)
    }

    companion object {
        private var instance: SpUtils? = null

        fun getInstance(): SpUtils {
            if (instance == null) {
                instance = SpUtils()
            }
            return instance!!
        }
    }


    fun <T> getValue(key:String,default: T): T {
        return findPreference(key,default)
    }

    fun <T> setValue(key:String,default:T) {
        putPreference(key, default)
    }

    private fun <T> findPreference(key:String, default: T) : T  = with(prefs){
        return when (default) {
            is Long -> getLong(key, default)
            is String -> getString(key, default)
            is Int -> getInt(key, default)
            is Boolean -> getBoolean(key, default)
            is Float -> getFloat(key, default)
            else -> throw IllegalArgumentException("Unsupport type")
        } as T
    }

    private fun <T> putPreference(name:String, default:T) = with(prefs.edit()) {
        when (default) {
            is Long -> putLong(name, default)
            is String -> putString(name, default)
            is Int -> putInt(name, default)
            is Boolean -> putBoolean(name, default)
            is Float -> putFloat(name, default)
            else -> throw IllegalArgumentException("Unsupport type")
        }.apply()
    }

}